import { Input } from "antd";
import { useState } from "react";

interface HotkeyInputProps {
  value?: string;
  onChange?: (value: string) => void;
}

const HotkeyInput: React.FC<HotkeyInputProps> = ({ value, onChange }) => {
  const [hotkey, setHotkey] = useState(value || "");

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    e.preventDefault();
    const keys = [];
    if (e.ctrlKey) keys.push("Ctrl");
    if (e.shiftKey) keys.push("Shift");
    if (e.altKey) keys.push("Alt");
    if (e.metaKey) keys.push("Win");

    let key = e.key.toUpperCase();
    if (key === " ") key = "SPACE";
    if (key === "ARROWLEFT") key = "Left";
    if (key === "ARROWRIGHT") key = "Right";
    if (key === "ARROWUP") key = "Up";
    if (key === "ARROWDOWN") key = "Down";
    if (!["CONTROL", "SHIFT", "ALT", "META"].includes(key)) {
      keys.push(key);
    }
    const newHotkey = keys.join(" + ");
    setHotkey(newHotkey);
    onChange?.(newHotkey);
  };

  return (
    <Input
      allowClear
      placeholder="请输入快捷键"
      value={hotkey}
      onKeyDown={handleKeyDown}
      onChange={(e) => setHotkey(e.target.value)}
      onClear={() => {
        setHotkey("");
        onChange?.("");
      }}
    />
  );
};

export default HotkeyInput;
